package com.mqstudy.activemq.config;

import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTopic;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jms.config.DefaultJmsListenerContainerFactory;
import org.springframework.jms.config.JmsListenerContainerFactory;
import org.springframework.jms.core.JmsTemplate;

import javax.jms.ConnectionFactory;
import javax.jms.Queue;
import javax.jms.Topic;

/**
 * ActiveMQ配置类
 */
@Configuration
public class ActiveMQConfig {
    
    // 队列和主题名称
    public static final String TEST_QUEUE = "test.queue";
    public static final String TEST_TOPIC = "test.topic";
    public static final String ORDER_QUEUE = "order.queue";
    public static final String USER_TOPIC = "user.topic";
    
    /**
     * 测试队列
     */
    @Bean
    public Queue testQueue() {
        return new ActiveMQQueue(TEST_QUEUE);
    }
    
    /**
     * 测试主题
     */
    @Bean
    public Topic testTopic() {
        return new ActiveMQTopic(TEST_TOPIC);
    }
    
    /**
     * 订单队列
     */
    @Bean
    public Queue orderQueue() {
        return new ActiveMQQueue(ORDER_QUEUE);
    }
    
    /**
     * 用户主题
     */
    @Bean
    public Topic userTopic() {
        return new ActiveMQTopic(USER_TOPIC);
    }
    
    /**
     * 点对点消息监听器容器工厂
     */
    @Bean
    public JmsListenerContainerFactory<?> queueListenerFactory(ConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setConcurrency("3-10"); // 最小3个消费者，最大10个消费者
        factory.setRecoveryInterval(1000L);
        return factory;
    }
    
    /**
     * 发布订阅消息监听器容器工厂
     */
    @Bean
    public JmsListenerContainerFactory<?> topicListenerFactory(ConnectionFactory connectionFactory) {
        DefaultJmsListenerContainerFactory factory = new DefaultJmsListenerContainerFactory();
        factory.setConnectionFactory(connectionFactory);
        factory.setPubSubDomain(true); // 设置为发布订阅模式
        factory.setConcurrency("1-5");
        factory.setRecoveryInterval(1000L);
        return factory;
    }
    
    /**
     * JMS模板配置
     */
    @Bean
    public JmsTemplate jmsTemplate(ConnectionFactory connectionFactory) {
        JmsTemplate jmsTemplate = new JmsTemplate(connectionFactory);
        jmsTemplate.setDeliveryMode(javax.jms.DeliveryMode.PERSISTENT); // 持久化消息
        jmsTemplate.setTimeToLive(60000); // 消息生存时间60秒
        return jmsTemplate;
    }
} 